/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.shipdream.lib.ohos.mvc;

import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.ability.fraction.FractionScheduler;

/**
 * FragmentTransaction .
 *
 * @author a
 * @version v
 */
public class FragmentTransaction {
    private FractionScheduler fractionScheduler;

    private TransactionListener transactionListener;

    public FragmentTransaction(FractionScheduler fractionScheduler, TransactionListener transactionListener) {
        this.fractionScheduler = fractionScheduler;
        this.transactionListener = transactionListener;
    }

    /**
     * add .
     *
     * @param containerViewId containerViewId
     * @param fragment        fragment
     * @param tag             tag
     * @return FragmentTransaction
     */
    public FragmentTransaction add(int containerViewId, Fraction fragment, String tag) {
        fractionScheduler.add(containerViewId, fragment, tag);
        // fractionScheduler.replace(containerViewId, fragment);
        FragmentManager.BackStackEntry backStackEntry = new FragmentManager.BackStackEntry(fragment, tag);
        transactionListener.replaceListener(backStackEntry);
        return this;
    }

    /**
     * replace .
     *
     * @param containerViewId containerViewId
     * @param fragment        fragment
     * @return FragmentTransaction
     */
    public FragmentTransaction replace(int containerViewId, Fraction fragment) {
        fractionScheduler.replace(containerViewId, fragment);
        return this;
    }

    /**
     * commit.
     */
    public void commit() {
        fractionScheduler.submit();
        transactionListener.commitListener();
    }

    /**
     * TransactionListener.
     */
    public interface TransactionListener {
        /**
         * replaceListener.
         *
         * @param backStackEntry backStackEntry
         */
        void replaceListener(FragmentManager.BackStackEntry backStackEntry);

        /**
         * removeListener .
         *
         * @param backStackEntry backStackEntry
         */
        void removeListener(FragmentManager.BackStackEntry backStackEntry);

        /**
         * commitListener .
         */
        void commitListener();
    }
}
